package com.soul.soulcommon.filter;

import com.soul.soulcommon.detail.OlderDetail;
import com.soul.soulcommon.dto.Jwt;
import com.soul.soulcommon.utils.JwtUtils;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletContext;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.security.core.context.SecurityContextHolder;
import java.io.IOException;
@Component
public class JwtAuthencationFilter extends OncePerRequestFilter {
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private ServletContext servletContext;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("Authorization");
        if(token == null){
            doFilter(request, response, filterChain);
            return ;
        }
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
            // 去掉 "Bearer " 前缀
        }
        //有token，验证token
        Integer userId = jwtUtils.getUserIdFromToken(token);
        String userName = jwtUtils.getUserNameFromToken(token);
        String userRole = jwtUtils.getRoleNameFromToken(token);
        System.out.println("userId:"+userId+"\n"+
                 "userName:"+userName+"\n"+
                 "userRole" + userRole+"\n");
        Jwt jwt = new Jwt();
        jwt.setId(userId);
        jwt.setUserName(userName);
        jwt.setRoleName(userRole);
        OlderDetail olderDetail = new OlderDetail(jwt);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(olderDetail, null, olderDetail.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        doFilter(request, response, filterChain);
    }
}
